package com.hkts.beltweigher.master.service.serviceimpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hkts.beltweigher.master.entity.Displaydata;
import com.hkts.beltweigher.master.entity.YbClassesAccumulate;
import com.hkts.beltweigher.master.entity.YbHourAccumulate;
import com.hkts.beltweigher.master.mapper.YbClassesAccumulateMapper;
import com.hkts.beltweigher.master.service.IDisplaydataService;
import com.hkts.beltweigher.master.service.IYbClassesAccumulateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkts.beltweigher.master.vo.DateStatisticsVo;
import com.hkts.beltweigher.master.vo.ReportStatisticsResultVo;
import com.hkts.beltweigher.utils.ExportExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hml
 * @since 2024-04-10
 */
@Service
@Transactional
@Slf4j
public class YbClassesAccumulateServiceImpl extends ServiceImpl<YbClassesAccumulateMapper, YbClassesAccumulate> implements IYbClassesAccumulateService {


    @Autowired
    private YbClassesAccumulateMapper ybClassesAccumulateMapper;
    @Autowired
    public IDisplaydataService iDisplaydataService;
    @Override
    public IPage<YbClassesAccumulate> selectPage(Page<YbClassesAccumulate> page, YbClassesAccumulate ybClassesAccumulate) {
        QueryWrapper<YbClassesAccumulate> query = Wrappers.query();
        return ybClassesAccumulateMapper.selectPage(page, query);
    }


    @Override
    public List<YbClassesAccumulate> selectList(YbClassesAccumulate ybClassesAccumulate) {
        QueryWrapper<YbClassesAccumulate> query = Wrappers.query();
        return ybClassesAccumulateMapper.selectList(query);
    }

    @Override
    public YbClassesAccumulate selectYbClassAccumulate() {
        QueryWrapper<YbClassesAccumulate> query = Wrappers.query();
        query.lambda().last("LIMIT 1").orderByDesc(YbClassesAccumulate::getId);
        return ybClassesAccumulateMapper.selectOne(query);
    }
    //报表统计
    @Override
    public Object reportStatistics(String startDate, String endDate) throws ParseException {
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        QueryWrapper<YbClassesAccumulate> query = Wrappers.query();
        query.lambda().ge(YbClassesAccumulate::getStatisticsDate,startDate);
        query.lambda().le(YbClassesAccumulate::getStatisticsDate,endDate);
        query.lambda().orderByAsc(YbClassesAccumulate::getModifyTime);
        List<YbClassesAccumulate> ybClassesAccumulates = ybClassesAccumulateMapper.selectList(query);
        List<ReportStatisticsResultVo> result=new ArrayList<>();
      //查询仪表统计
       // List<String> collect = ybClassesAccumulates.stream().map(YbClassesAccumulate::getInstrumentName).distinct().collect(Collectors.toList());
        Displaydata displaydata=new Displaydata();
        displaydata.setDataStatus(true);

        List<Displaydata> displaydata1 = iDisplaydataService.selectList(displaydata);
        List<String> collect = displaydata1.stream().map(Displaydata::getInstrumentName).distinct().collect(Collectors.toList());

        for (int i = 0; i <collect.size() ; i++) {
            String instrumentName = collect.get(i);
            List<YbClassesAccumulate> instrumentNameList = ybClassesAccumulates.stream().filter(ybClassesAccumulate -> ybClassesAccumulate.getInstrumentName().equals(instrumentName)).collect(Collectors.toList());
            List<Date> dateList = instrumentNameList.stream().map(YbClassesAccumulate::getStatisticsDate).distinct().collect(Collectors.toList());
            List<String> dateTimeList=new ArrayList<>();
            for (int j = 0; j <dateList.size() ; j++) {
                dateTimeList.add(format.format(dateList.get(j)));
            }
            ReportStatisticsResultVo vo=new ReportStatisticsResultVo();
            vo.setInstrumentName(instrumentName);
            List<DateStatisticsVo> dateStatisticsList=new ArrayList<>();
            for (int j = 0; j <dateTimeList.size() ; j++) {
                String dateTime = dateTimeList.get(j);
                List<YbClassesAccumulate> bc1 = ybClassesAccumulates.stream().filter(ybClassesAccumulate ->
                        ybClassesAccumulate.getClasses().equals("BC1")&&
                                ybClassesAccumulate.getDateTime().equals(dateTime)&&ybClassesAccumulate.getInstrumentName().equals(instrumentName)).collect(Collectors.toList());
                List<YbClassesAccumulate> bc2 = ybClassesAccumulates.stream().filter(ybClassesAccumulate -> ybClassesAccumulate.getClasses().equals("BC2")
                        &&ybClassesAccumulate.getDateTime().equals(dateTime)&&ybClassesAccumulate.getInstrumentName().equals(instrumentName)).collect(Collectors.toList());
                DateStatisticsVo dateStatisticsVo=new DateStatisticsVo();
                dateStatisticsVo.setRecortDate(dateTime);
                if(bc1.size()>0){
                    dateStatisticsVo.setClass1(bc1.get(0).getClassesValue());
                }
                if(bc2.size()>0){
                    dateStatisticsVo.setClass2(bc2.get(0).getClassesValue());
                }
                dateStatisticsList.add(dateStatisticsVo);
            }
            vo.setList(dateStatisticsList);
            result.add(vo);
        }

        return result;
    }
    //导出
    @Override
    public void exportReport(String startDate, String endDate,String classes, HttpServletResponse response) throws ParseException, IOException {
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Date parse = format.parse(endDate);
        Calendar calendar   =   new GregorianCalendar();
        calendar.setTime(parse);
        calendar.add(Calendar.DATE,1);

        QueryWrapper<YbClassesAccumulate> query = Wrappers.query();
        query.lambda().ge(YbClassesAccumulate::getStatisticsDate,startDate);
        query.lambda().le(YbClassesAccumulate::getStatisticsDate,endDate);
        query.lambda().eq(StringUtils.isNotBlank(classes),YbClassesAccumulate::getClasses,classes);

        List<YbClassesAccumulate> ybClassesAccumulates = ybClassesAccumulateMapper.selectList(query);
        List<Map<String,String>> data=new ArrayList<>();
        String[] headers=new String[]{"日期","班次标识","仪表名称","数值","调整时间","用户的班次名称"};
        for (int i = 0; i <ybClassesAccumulates.size() ; i++) {
            Map<String,String> map=new HashMap();
            map.put("日期",ybClassesAccumulates.get(i).getDateTime());
            map.put("班次标识",ybClassesAccumulates.get(i).getClasses());
            map.put("仪表名称",ybClassesAccumulates.get(i).getInstrumentName());
            map.put("数值",ybClassesAccumulates.get(i).getClassesValue()==null?null:ybClassesAccumulates.get(i).getClassesValue().toString());
            map.put("调整时间",ybClassesAccumulates.get(i).getModifyTime().format(df));
            map.put("用户的班次名称",ybClassesAccumulates.get(i).getClassesName());
            data.add(map);
        }
        XSSFWorkbook wb = new XSSFWorkbook();
        String fileName = "班组累计.xlsx";
        ExportExcelUtil.exportExcel(wb,0,fileName,headers,data);
        response.setContentType("application/octet-stream");
        //设置导出Excel的名称
        response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
        //刷新缓冲
        response.flushBuffer();
        //workbook将Excel写入到response的输出流中，供页面下载该Excel文件
        wb.write(response.getOutputStream());
        //关闭workbook
        wb.close();
    }
}
